import websocket from '@/utils/msg/websocketUtils.js'
import { doesNotThrow } from 'assert';

// websocket工具类
class WebSocketUtil {

	/**
	 * @param {Object} url 连接请求地址
	 * @param {Object} time 心跳时间
	 * @param {Object} clientId 设备id
	 */
	constructor(url, time, clientId) {
		this.url = url
		this.timeout = time
		this.clientId = clientId

		this.heartbeatInterval = null; // 心跳定时器
		this.lockReconnect = false; // 避免重复连接标识
		this.is_open_socket = false //避免重复连接

		this.socketTask = null //websocket对象

		try {
			return this.connectSocketInit()
		} catch (e) {
			//console.log('catch');
			//避免重复重连
			this.lockReconnect = false
			//断线重连
			this.reconnect();
		}
	}

	// 初始化websocket连接
	connectSocketInit() {
		this.socketTask = uni.connectSocket({
			url: this.url,
			header: {
				'Authorization': 'Bearer=' + this.token // 在请求头中携带token
				//'content-type': 'application/json',
				//token: this.token, //您可根据如本地存储或者vuex再此处使用逻辑或 来插入token
			},
			success: () => {
				console.log("正准备建立websocket中...");
				//心跳检测
				//this.start()

				// 返回实例
				return this.socketTask
			},

		});

		// 监听websocket连接打开事件
		this.socketTask.onOpen((res) => {
			//console.log('websocket连接已打开');
			console.log("WebSocket连接正常！");
			//关闭心跳检测定时器
			clearTimeout(this.heartbeatInterval)
			this.heartbeatInterval = null;
			//1，第一次连接
			var loginData = {
				type: 1,
				
				msg: {
					userId: uni.getStorageSync('userId'),
					token: uni.getStorageSync('token'),
					username: "123",
					password: "123",
					clientId: this.clientId
				}
			}
			//登录
			var that = this
			this.socketTask.send({
				data: JSON.stringify(loginData),
				async success() {
					console.log('登录成功！开始心跳检测')
					//连接成功，开始心跳检测
					that.startHeartbeat(); // 开始心跳检测
				},
			});

		});

		// 监听websocket接收到服务器消息事件
		/* uni.onSocketMessage((res) => {
			const message = res.data;
			console.log('接收到消息:', message);
			// 处理接收到的消息
			this.handleMessage(message);
		}); */

		// 监听websocket关闭事件
		this.socketTask.onClose(() => {
			console.log('websocket连接已关闭');
			this.stopHeartbeat(); // 停止心跳检测
			// if (!this.lockReconnect) {
			// 	// 避免重复连接
			// 	this.reconnect(); // 断线自动重连
			// }
		});

		// 监听websocket错误事件
		this.socketTask.onError((res) => {
			console.error('websocket连接错误:');
			// 发生错误时处理
			
			this.handleError(res);
		});
	}

	// 发送消息
	send(value) {
		if (this.socketTask && this.socketTask.readyState === 1) {
			var result = false
			var that = this
			this.socketTask.send({
				data: JSON.stringify(value.data),
				success: () => {
					result = true
					console.log('发送消息成功:', message);
				},
				fail: (err) => {
					uni.$showMsg('发送失败，请重新发送！')
					//避免重复重连
					this.lockReconnect = false
					//断线重连
					this.reconnect();
				}
			})
			return result

		} else {
			console.warn('websocket连接尚未建立或已关闭');
			//避免重复重连
			this.lockReconnect = false
			//断线重连
			this.reconnect();
		}
	}

	// 关闭连接
	close(isReconnect = '2', time = 1000) {
		if (this.socketTask) {
			console.log('断开了。。。')
			this.socketTask.close();
			this.socketTask = null;

			if (isReconnect == '2' && !this.lockReconnect) {
				//避免重复重连
				this.lockReconnect = false
				//断线重连
				this.reconnect(time);
			}
		}
	}

	// 开始心跳检测
	startHeartbeat() {
		this.heartbeatInterval = setInterval(() => {
			var sendData = {
				type: 2,
				msg: {
					userId: uni.getStorageSync('userId'),
					username: "123",
					password: "123",
					clientId: this.clientId
				}
			}
			//发送心跳检测
			this.socketTask.send({
				data: JSON.stringify(sendData),
				async success() {
					// console.log('心跳包')
				},
			});

		}, this.timeout); // 每5秒发送一次心跳包
	}

	// 停止心跳检测
	stopHeartbeat() {
		clearInterval(this.heartbeatInterval);
		this.heartbeatInterval = null;
	}

	// 断线自动重连
	reconnect(time = 1000) {
		//console.log('想要重连')
		if (this.lockReconnect) {
			return;
		}
		//console.log('准备重连')
		this.lockReconnect = true;
		setTimeout(() => {
			//this.connectSocketInit(); // 重新建立连接
			//console.log('责怪在撒旦法')
			uni.$connectSocketInit.connectSocket(uni.$nettyPort)
			this.lockReconnect = false;
		}, time); // 4秒后尝试重新连接
	}

	// 处理接收到的消息
	receiveMsg() {
		// 处理消息逻辑
		var that = this
		return new Promise(resolve => {
			that.socketTask.onMessage((res) => {
				var msg = JSON.parse(res.data)
				resolve(msg)
			});
		})
	}

	// 处理错误
	handleError(err) {
		// 处理错误逻辑
		this.close('2', 1500)
		
		//uni.myWebsocket = ''
		//断线重连
		//this.close();

	}
}

module.exports = WebSocketUtil